package com.github.fancyideas.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fancyideas.exceptions.AppException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class JsonChangeUtil {

    public static Object jsonToObj(Object obj, String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, obj.getClass());
        } catch (IOException e) {
            log.error("Jackson 转换对象失败：{}", e.getMessage());
            throw new AppException("Jackson 转换对象失败");
        }
    }

    public static String objToJson(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("Jackson 转换对象失败：{}", e.getMessage());
            throw new AppException("Jackson 转换对象失败");
        }
    }

}
